package lg.minecraft.plugin.entityclear.command;

import lg.minecraft.plugin.entityclear.manager.EntityTaskManager;
import lg.minecraft.plugin.entityclear.task.EntityClearTask;
import lg.minecraft.plugin.library.command.CommandContext;
import lg.minecraft.plugin.library.command.SubCommand;
import org.bukkit.command.CommandSender;

import java.util.ArrayList;
import java.util.List;

/**
 * 手动触发清理任务的命令
 */
public class TriggerCommand extends SubCommand {

    public TriggerCommand() {
        super("trigger");
    }

    @Override
    public String getDescription() {
        return "调用任务进行实体清理";
    }

    @Override
    public void onCommand(CommandContext context) {
        CommandSender sender = context.getSender();
        if (context.getArgLength() == 0) {
            sender.sendMessage("用法: /lgec run <任务名>");
            return;
        }

        List<String> list = new ArrayList<>();
        List<EntityClearTask> taskList = new ArrayList<>();
        for (String taskName : context.getArgs()) {
            EntityClearTask task = EntityTaskManager.INSTANCE.getTask(taskName);
            if (task == null) {
                list.add(taskName);
            } else {
                taskList.add(task);
            }
        }

        if (!list.isEmpty()) {
            sender.sendMessage("[§a实体清理§f] 未找到任务: " + list);
        }

        if (taskList.isEmpty()) {
            return;
        }

        int count = 0;
        long start = System.currentTimeMillis();
        for (EntityClearTask task : taskList) {
            count += task.clearEntities();
        }
        long end = System.currentTimeMillis();
        sender.sendMessage("[§a实体清理§f] 已手动清理 " + count + " 个实体，耗时 " + (end - start) + " 毫秒");
    }

    @Override
    public List<String> onTabComplete(CommandContext context) {
        ArrayList<String> list = new ArrayList<>(EntityTaskManager.INSTANCE.getKeySet());
        int max = Math.max(0, context.getArgLength() - 1);
        for (int i = 0; i < max; i++) {
            list.remove(context.getArg(i));
        }
        return list;
    }

}
